package com.iteye.trafficRecorder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

/**
 * 文本HTTP请求回调包装类
 * @author chen_weihua
 *
 */
public class CallbackWrapper implements Runnable {
 
	protected ResponseListener callbackActivity;
	protected HttpResponse response;
	protected Throwable error;
	protected String charset;
	private boolean success;
	private String result;
	private Object tagObj;
 
	public CallbackWrapper(ResponseListener callbackActivity) {
		success = false;
		this.callbackActivity = callbackActivity;
	}
	
	public Object getTagObj() {
		return tagObj;
	}

	public void setTagObj(Object tagObj) {
		this.tagObj = tagObj;
	}

	/**
	 * 在UI线程中调用
	 */
	public void run() {
		if (success) {
			onResponseSuccess();
		} else {
			callbackActivity.onResponseFailed(response, error, tagObj);
		}
	}
	
	public void setCharset(String charset) {
		this.charset = charset;
	}
 
	public void setResponse(HttpResponse response) {
		this.response = response;
	}

	public void setError(Throwable error) {
		this.error = error;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	protected void setResult() throws Exception {
		HttpEntity entity = response.getEntity();
		result = EntityUtils.toString(entity);
	}
	
	protected void onResponseSuccess() {
		callbackActivity.onResponseSuccess(response, result, tagObj);
	}
 
}
